package com.bootdo.app.common.runner;

import com.bootdo.app.common.config.AuthConfig;
import com.bootdo.app.common.utils.RSAKeyCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
  * @auther: Along
  * @description: JWT AUTH 数据加载
  * @Date: created in 2020/4/5 0:10
  */
@Component
public class JwtAuthRunner implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(JwtAuthRunner.class);

//    @Autowired
//    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private AuthConfig authConfig;

    @Override
    public void run(String... args) throws Exception {
        if(!authConfig.getOpen()){
            return;
        }
        logger.info("初始化加载jwt-pubKey&jwt-priKey");
//        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
//        if(opsForHash.hasKey(JWTConstants.JWT_REDIS_KEY,JWTConstants.JWT_PUB_HASH_KEY) && opsForHash.hasKey(JWTConstants.JWT_REDIS_KEY,JWTConstants.JWT_PRI_HASH_KEY)){
//            logger.info("从redis中读取jwt公私钥数据");
//            byte[] pubKeyByte = RSAKeyCreator.base64Decode((String)opsForHash.get(JWTConstants.JWT_REDIS_KEY,JWTConstants.JWT_PUB_HASH_KEY));
//            byte[] priKeyByte = RSAKeyCreator.base64Decode((String)opsForHash.get(JWTConstants.JWT_REDIS_KEY,JWTConstants.JWT_PRI_HASH_KEY));
//            authConfig.setPubKeyByte(pubKeyByte);
//            authConfig.setPriKeyByte(priKeyByte);
//            logger.info("AuthConfig数据加载完成");
//        }else{
//            logger.info("向redis初始化jwt公私钥数据");
//            Map<String, byte[]> pubAndPriKey = RSAKeyCreator.createPubKeyAndPriKey(authConfig.getRsaSecret());
//            byte[] pubKeyByte = pubAndPriKey.get("pub");
//            byte[] priKeyByte = pubAndPriKey.get("pri");
//            Map<String,String> map = new HashMap<>();
//            map.put(JWTConstants.JWT_PUB_HASH_KEY,RSAKeyCreator.base64Encode(pubKeyByte));
//            map.put(JWTConstants.JWT_PRI_HASH_KEY,RSAKeyCreator.base64Encode(priKeyByte));
//            opsForHash.putAll(JWTConstants.JWT_REDIS_KEY,map);
//            authConfig.setPubKeyByte(pubKeyByte);
//            authConfig.setPriKeyByte(priKeyByte);
//            logger.info("redis初始化jwt数据完成");
//        }
        Map<String, byte[]> pubAndPriKey = RSAKeyCreator.createPubKeyAndPriKey(authConfig.getRsaSecret());
        byte[] pubKeyByte = pubAndPriKey.get("pub");
        byte[] priKeyByte = pubAndPriKey.get("pri");
        authConfig.setPubKeyByte(pubKeyByte);
        authConfig.setPriKeyByte(priKeyByte);
        logger.info("初始化jwt数据完成");

    }
}
